// utils/wxLogin.ts
import Taro from '@tarojs/taro';
import { request } from './request';

class WxLogin {
  // 微信登录
  static async login(): Promise<string> {
    try {
      const res = await Taro.login();
      if (!res.code) throw new Error('微信登录失败');

      const loginRes = await request.post(
        '/member/auth/weixin-mini-app-login',
        { code: res.code },
        false
      );

      Taro.setStorageSync('token', loginRes.token);
      return loginRes.token;
    } catch (err) {
      console.error(err);
      Taro.showToast({ title: '微信登录失败', icon: 'none' });
      throw err;
    }
  }

  // 刷新 token
  static async refreshToken(): Promise<string> {
    try {
      const oldToken = Taro.getStorageSync('token');
      const res = await request.post(
        '/member/auth/refresh-token',
        { token: oldToken },
        false
      );
      Taro.setStorageSync('token', res.token);
      return res.token;
    } catch (err) {
      console.error('刷新 token 失败', err);
      throw err;
    }
  }

  /**
   * 退出登录
   * @param redirect 是否跳转登录页，false 可刷新当前页或返回上一页
   */
  static async logout(redirect: boolean = true) {
    try {
      // 调用后端退出接口，需要带 token
      await request.post('/member/auth/logout', {}, true);

      // 清理本地缓存
      Taro.removeStorageSync('token');

      Taro.showToast({ title: '已退出登录', icon: 'none' });

      if (redirect) {
        // 跳转登录页
        Taro.reLaunch({ url: '/pages/login/index' });
      } else {
        // 刷新当前页
        // const currentPages = Taro.getCurrentPages();
        // const currentPage = currentPages[currentPages.length - 1];
        // currentPage?.onLoad?.(currentPage.options);
      }
    } catch (err) {
      console.error('退出登录失败', err);
      Taro.showToast({ title: '退出登录失败', icon: 'none' });
    }
  }
}

export { WxLogin };
